import { JSEncrypt } from 'jsencrypt'
import NodeRSA from 'node-rsa'
import { SHA256, AES, enc, mode, pad } from 'crypto-js'

// SHA256处理
export const sha256 = (content, publicKey) => {
  const res = SHA256(content)
  const sha256Str = res.toString()
  return sha256Str
}
// rsa公钥加密
export const rsa = (content, publicKey) => {
  const encrypt = new JSEncrypt({
    default_key_size: 1024,
    default_public_exponent: 65537
  })
  encrypt.setPublicKey(publicKey)
  return encrypt.encrypt(content)

  // const key = new NodeRSA({ b: 1024 })
  // key.importKey(publicKey, 'pkcs8-public-pem')
  // key.setOptions({ encryptionScheme: 'pkcs1' })//指定加密格式
  // return key.encrypt(content, 'base64')
}
// rsa私钥解密
export const decrypt = (content, decryptId) => {
  const encrypt = new JSEncrypt({
    default_key_size: 1024,
    default_public_exponent: 65537
  })
  encrypt.setPrivateKey(decryptId)
  return encrypt.decrypt(content)

  // const key = new NodeRSA({ b: 1024 })
  // key.importKey(decryptId, 'pkcs8-private-pem')
  // key.setOptions({ encryptionScheme: 'pkcs1' })//指定加密格式
  // return key.decrypt(content, 'utf8')
}

// rsa公钥解密
export const decryptPublic = (content, decryptId) => {
  const key = new NodeRSA({ b: 1024 })
  key.importKey(decryptId, 'pkcs8-public-pem')
  key.setOptions({ encryptionScheme: 'pkcs1' })// 指定加密格式
  return key.decryptPublic(content, 'utf8')
}

// AES加密
export const AESEncode = (content, key = '1234567890123456') => {
  const keyStr = enc.Utf8.parse(key.substring(0, 16))
  const iv = enc.Utf8.parse(key.substring(16))
  const str = enc.Utf8.parse(content)
  const encrypted = AES.encrypt(str, keyStr, {
    mode: mode.CBC,
    padding: pad.Pkcs7,
    iv
  })
  return encrypted.toString()
}

// AES解密
export const AESDecode = (content, key = '1234567890123456') => {
  const keyStr = enc.Utf8.parse(key.substring(0, 16))
  const iv = enc.Utf8.parse(key.substring(16))
  const decrypt = AES.decrypt(content, keyStr, {
    mode: mode.CBC,
    padding: pad.Pkcs7,
    iv
  })
  return enc.Utf8.stringify(decrypt).toString()
}
